package com.itheima.reggie.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.EmployeeHolder;
import com.itheima.reggie.domain.Employee;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//自定义的拦截器
@Component //将拦截器放入容器
public class LoginCheckInterceptor implements HandlerInterceptor {
    //进入controller之前拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //验证用户是否登录了 如果登录session域中就会保存信息
        Employee employee = (Employee) request.getSession().getAttribute("SESSION_EMPLOYEE");
        if (employee == null) {
            //没有登录过 向前端返回约定好的NOTLOGIN
            ResultInfo resultInfo = ResultInfo.error("NOTLOGIN");
            String json = new ObjectMapper().writeValueAsString(resultInfo);
            response.getWriter().write(json);
            return false;//禁止通行
        } else {
            //执行到这里请求正常放行的时候,将employee对象放入到ThreadLocal中
             EmployeeHolder.set(employee);
            //正常放行
            return true;

        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //请求即将离开服务器之前,移除本次ThreadLocal中的employee对象,ThreadLocal是一块内存
        EmployeeHolder.remove();
    }
}
